package terminal.communication;

import java.net.BindException;

import org.jboss.remoting.InvalidConfigurationException;
import org.jboss.remoting.InvokerLocator;
import org.jboss.remoting.transport.Connector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class Server implements ApplicationContextAware {

	private static final Logger L = LoggerFactory.getLogger(Server.class);

	private ApplicationContext context;

	private Connector connector = null;

	private String locatorURI;

	public Server() {
		L.debug("Tworzę Server");
		L.debug("Utworzono Server");
	}

	public void setUp(String locatorURI) throws BindException {
		L.info("Inicjalizuję serwer");

		try {
			InvocationHandler invocationHandler = context.getBean(InvocationHandler.class);
			InvokerLocator invokerLocator = null;
			invokerLocator = new InvokerLocator("socket://" + locatorURI);
			connector = new Connector(invokerLocator);
			connector.create();
			connector.addInvocationHandler(locatorURI, invocationHandler);
			this.locatorURI = locatorURI;
			if (!connector.isStarted()) {
				L.info("Otwieram serwer");
				connector.start();
			}
		} catch (BindException e) {
			L.error(e.getMessage());
			throw e;
		} catch (InvalidConfigurationException e) {
			L.error(e.getMessage());
		} catch (Exception e) {
			L.error(e.getMessage());
		}
	}

	public void shutdownServer() {
		L.info("Zamykam serwer");

		if (connector != null) {
			connector.stop();
		}
	}

	public String getLocatorURI() {
		return locatorURI;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.context = applicationContext;
	}
}
